package com.yilifang.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yilifang.dao.cluster.ClusterDirectSqlMapper;
import com.yilifang.dao.master.MasterDirectSqlMapper;
import com.yilifang.service.OaNewsApiService;
import com.yilifang.service.ZbdlApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhuan on 2018-09-14.
 */
@Slf4j
@Service
public class OaNewsApiServiceImpl implements OaNewsApiService {

    @Autowired
    ClusterDirectSqlMapper clusterDirectSqlMapper;

    //redis操作
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //redis操作
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * OA新闻公告和内容
     * @param page
     * @param size
     * @return
     */
    public String getOANews(Integer page,Integer size){
        //缓存
        String key = "OANews" + page + size;
        String oaNewsJson = stringRedisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(oaNewsJson)){
            List<Map<String, Object>> oaNews = clusterDirectSqlMapper.selectOANews(page, size);
            oaNewsJson = JSON.toJSONString(oaNews);
            stringRedisTemplate.opsForValue().set(key,oaNewsJson,20, TimeUnit.MINUTES);
        }

        //无缓存
//        List<Map<String, Object>> oaNews = clusterDirectSqlMapper.selectOANews(page, size);
//        String oaNewsJson =  JSON.toJSONString(oaNews);
        return  oaNewsJson;
    }

    @Override
    public Object getOANewsList(Integer page, Integer size) {
        //缓存
        String key = "OANewsList" + page + size;
        Object oaNewsListJson = redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(oaNewsListJson)){
            List<Map<String, Object>> oaNewsList = clusterDirectSqlMapper.selectOANewsList(page, size);
            Map<String, Object> oaNewsCount = clusterDirectSqlMapper.selectOaNewsCount();

            Map<String,Object> oaNewsListAndCount = new HashMap<>();
            oaNewsListAndCount.put("oaNewsCount",oaNewsCount.get("NEWSCOUNT"));
            oaNewsListAndCount.put("oaNewsList",oaNewsList);


            oaNewsListJson = JSONObject.toJSON(oaNewsListAndCount);
            redisTemplate.opsForValue().set(key,oaNewsListJson,20, TimeUnit.MINUTES);
        }
        log.info(oaNewsListJson.toString());
        return oaNewsListJson;
    }

    @Override
    public Object getOANewsBody(String id) {
        Map<String, Object> oaNewsBodyMap = clusterDirectSqlMapper.selectOANewsBodyById(id);
        return JSON.toJSON(oaNewsBodyMap);
    }
}
